/**
 * @author chenyz
 */

domtab = {
	flagClass : 'domtab',
	tabClass : 'domtabs',
	contentClass : 'div',
	activeClass : 'active',
	defaultTabWidth : '180',
	tabid : 1,

	init : function() {
		domtab.tabid = 1;
		domtab.titleRoot = document.getElementsByClassName(domtab.tabClass)[0];
		domtab.contentRoot = document.getElementsByClassName(domtab.flagClass)[0];
	},

	addNewTab : function(title, content, type, source, path) {
		// create nodes
		var titleDOM = domtab.createTitle(title, type, path);
		var contentDOM = domtab.createContent(title, content);

		// add nodes to dom
		domtab.titleRoot.appendChild(titleDOM);
		domtab.contentRoot.appendChild(contentDOM);

		// register event
		domtab.addEvent(titleDOM, "click", domtab.showContent, false);

		var activeTitleDOM = domtab.getTitleDOM(domtab.activeFile);
		var activeContentDOM = domtab.getContentDOM(domtab.activeFile);

		// set display
		domtab.cssjs("remove", activeTitleDOM, domtab.activeClass);
		domtab.changeTab(activeContentDOM, 0);
		domtab.cssjs("add", titleDOM, domtab.activeClass);
		domtab.changeTab(contentDOM, 1);

		// log current status
		domtab.activeFile = "id" + domtab.tabid;
		domtab.tabid++;

		domtab.adjustTab();

		if (source != "FROMLOCAL") {
			var code = domtab.getContent(domtab.activeFile);
			var cm = CodeMirror.fromTextArea(code, {
				lineNumbers : true,
				matchBrackets : true,
				fixedGutter: true,
				lineWrapping: true,
				extraKeys : {
					"Alt-Enter" : "autocomplete",
					"'>'" : function(cm) {
						cm.closeTag(cm, '>');
					},
					"'/'" : function(cm) {
						cm.closeTag(cm, '/');
					},
					extraKeys: {"Ctrl-Q": function(cm){foldFunc(cm, cm.getCursor().line);}}
				},
				onChange : function(editor, changes) {
					var t = domtab.getTitle(domtab.activeFile);
					var status = t.getAttribute("status");
					if (status == "UNCHANGED") {
						t.setAttribute("status", "MODIFIED");
						t.innerHTML = "*" + t.innerHTML;
					}
				},
				onCursorActivity : function(editor) {
					// update the status bar
					var corrds = editor.cursorCoords(true);
					var charCoords = editor.coordsChar(corrds);
					$(document).ready(function() {
						$('#statusbar #row').html(charCoords.line + 1);
						$('#statusbar #column').html(charCoords.ch + 1);
					});
					// bind matching highlighting
					editor.matchHighlight("CodeMirror-matchhighlight");
					// bind highlighting active line
					editor.setLineClass(hlLine, null, null);
					hlLine = editor.setLineClass(editor.getCursor().line, null,
							"activeline");
				},
				onKeyEvent : function(cm, e) {
					if (e.type == 'keydown') {
						var c = e.keyCode || e.which;
						if (c == 190 || c == 191) {
							try {
								cm.closeTag(cm, c == 190 ? '>' : '/');
								e.stop();
								return true;
							} catch (e) {
								if (e != CodeMirror.Pass)
									throw e;
							}
						}
					}
					return false;
				},
			});
			var hlLine = cm.setLineClass(0, "activeline");
			cm.setOption("mode", type);
			var foldFunc = "";
			if(type == "text/javascript") {
				foldFunc = CodeMirror.newFoldFunction(CodeMirror.braceRangeFinder);
			} else if(type == "text/html") {
				foldFunc = CodeMirror.newFoldFunction(CodeMirror.tagRangeFinder);
			}
			cm.setOption("onGutterClick", foldFunc);
			pf.loadCMPF(cm);
			
			// hide the spacer
			var spacer = document.getElementById("spacer");
			spacer.style.display = "none";
			
			// show and refresh the status bar
			var statusBar = document.getElementById("statusbar");
			statusBar.style.display = "block";
			var row = document.getElementById("row");
			var column = document.getElementById("column");
			row.innerHTML = 1;
			column.innerHTML = 1;
		}
	},

	showContent : function(e) {
		var title = domtab.getTarget(e);
		var id = title.href.match(/#(\w.+)/)[1];
		var targetTitleDOM = domtab.getTitleDOM(id);
		var targetContentDOM = domtab.getContentDOM(id);

		var activeTitleDOM = domtab.getTitleDOM(domtab.activeFile);
		var activeContentDOM = domtab.getContentDOM(domtab.activeFile);

		// change display
		domtab.changeTab(activeContentDOM, 0);
		domtab.cssjs('remove', activeTitleDOM, domtab.activeClass);
		domtab.changeTab(targetContentDOM, 1);
		domtab.cssjs("add", targetTitleDOM, domtab.activeClass);

		// update log
		domtab.activeFile = id;
		
		// update the status bar's row & column
		var row = document.getElementById("row");
		var column = document.getElementById("column");
		row.innerHTML = 1;
		column.innerHTML = 1;

		e.preventDefault();
	},
	
	showContent_helper : function(id) {
		var targetTitleDOM = domtab.getTitleDOM(id);
		var targetContentDOM = domtab.getContentDOM(id);

		var activeTitleDOM = domtab.getTitleDOM(domtab.activeFile);
		var activeContentDOM = domtab.getContentDOM(domtab.activeFile);

		// change display
		domtab.changeTab(activeContentDOM, 0);
		domtab.cssjs('remove', activeTitleDOM, domtab.activeClass);
		domtab.changeTab(targetContentDOM, 1);
		domtab.cssjs("add", targetTitleDOM, domtab.activeClass);

		// update log
		domtab.activeFile = id;
		
		// update the status bar's row & column
		var row = document.getElementById("row");
		var column = document.getElementById("column");
		row.innerHTML = 1;
		column.innerHTML = 1;

		e.preventDefault();
	},

	closeTab : function(e) {
		var title = domtab.getTarget(e).previousSibling;
		var id = title.href.match(/#(\w.+)/)[1];
		domtab.closeTabHelper(id);
		
		// if all tab has been closed, show the spacer tab and empty the activeFile content
		var ids = domtab.getAllOpenedTabId();
		if(!ids || ids.length == 0) {
			var spacer = document.getElementById("spacer");
			spacer.style.display = "block";
		}
		e.preventDefault();
		
		// if there is no tab left, show spacer, hide status bar and empty activeFile content
		var ids = domtab.getAllOpenedTabId();
		if(!ids || ids.length == 0) {
			// hide the spacer
			var spacer = document.getElementById("spacer");
			spacer.style.display = "block";
			
			// show and refresh the status bar
			var statusBar = document.getElementById("statusbar");
			statusBar.style.display = "none";
		} else {
			var row = document.getElementById("row");
			var column = document.getElementById("column");
			row.innerHTML = 1;
			column.innerHTML = 1;
		}
	},

	closeTabHelper : function(id) {
		// save or not
		var closeCodeMirror = domtab.getCodeMirror(id);
		var closeTitle = domtab.getTitle(id);
		if (closeTitle.getAttribute("status") == "MODIFIED") {
		  control.save_helper(id);
		  /*
			alert("Close Unsaved Files");
			closeCodeMirror.save();
			var bb = new BlobBuilder();
			bb.append(closeCodeMirror.getValue());
			var type = filefolder.getMIMEType(id);
			saveAs(bb.getBlob(type + ";charset=utf-8"), id);
			*/
		}

		var targetTitleDOM = domtab.getTitleDOM(id);
		var targetContentDOM = domtab.getContentDOM(id);
		if (id == domtab.activeFile) {
			var nextTitleDOM = targetTitleDOM.nextSibling;
			var nextContentDOM = targetContentDOM.nextSibling;

			var previousTitleDOM = targetTitleDOM.previousSibling;
			var previousContentDOM = targetContentDOM.previousSibling;

			if (nextTitleDOM) {
				var nextId = nextTitleDOM.getAttribute("id");
				domtab.cssjs("add", nextTitleDOM, domtab.activeClass);
				domtab.changeTab(nextContentDOM, 1);
				domtab.activeFile = nextId;
			} else if (previousTitleDOM && previousTitleDOM.nodeName == "LI") {
				var previousId = previousTitleDOM.getAttribute("id");
				domtab.cssjs("add", previousTitleDOM, domtab.activeClass);
				domtab.changeTab(previousContentDOM, 1);
				domtab.activeFile = previousId;
			} else
				domtab.activeFile = "";
		}

		targetTitleDOM.parentNode.removeChild(targetTitleDOM);
		targetContentDOM.parentNode.removeChild(targetContentDOM);
		domtab.adjustTab();
	},

	adjustTab : function() {
		var info = domtab.getWidthInfo();
		var width = info.width.split('p')[0];
		var number = info.number;
		if (number <= 5) {
			// adjust
			domtab.setTabWidth(domtab.defaultTabWidth);
			// record
			domtab.currentTabWidth = domtab.defaultTabWidth;
		} else {
			var new_width = (width / number + 15);
			// adjust
			domtab.setTabWidth(new_width);
			// record
			domtab.currentTabWidth = new_width;
		}
	},

	/* helper method */
	getTarget : function(e) {
		var target = window.event ? window.event.srcElement : e ? e.target
				: null;
		if (!target) {
			return false;
		}
		return target;
	},
	createTitle : function(_title, _filetype, _path) {
	  
	    
		var title = document.createElement("li");
		title.setAttribute("id", "id" + domtab.tabid);
		title.appendChild(document.createElement("a"));
		var title_a = title.getElementsByTagName("a")[0];
		title.appendChild(document.createElement("img"));
		var img = title.getElementsByTagName("img")[0];
		img.setAttribute("src", "./picture/close_idle.png");
		img
				.setAttribute("onMouseOver",
						"this.src='./picture/close_active.png'");
		img.setAttribute("onMouseOut", "this.src='./picture/close_idle.png'");
		domtab.addEvent(img, "click", domtab.closeTab, false);
		// title_a.setAttribute("href", "#"+_title);
		title_a.setAttribute("href", "#" + "id" + domtab.tabid);
		title_a.setAttribute("name", _title);
		title_a.setAttribute("title", _title);
		title_a.setAttribute("path", _path);
		title_a.setAttribute("status", "UNCHANGED");
		title_a.innerHTML = _title;
		
		if(!_path)
	    title_a.setAttribute("from_existing_server", "true");
	    
	    
		// figure out file type
		if (!_filetype) {
			title_a.style.backgroundImage = "url(./picture/blank.png)";
		} else if (_filetype == "text/css") {
			title_a.style.backgroundImage = "url(./picture/css.png)";
		} else if (_filetype == "text/html") {
			title_a.style.backgroundImage = "url(./picture/html.png)";
		} else if (_filetype == "text/javascript") {
			title_a.style.backgroundImage = "url(./picture/js.png)";
		} else {
			title_a.style.backgroundImage = "url(./picture/blank.png)";
		}

		return title;
	},
	createContent : function(_title, _content) {
		var content = document.createElement("div");
		// content.setAttribute("id", _title.replace(".", "-"));
		content.setAttribute("id", "id" + domtab.tabid);
		content.setAttribute("class", "window");
		var code = document.createElement("textarea");
		content.appendChild(code);
		// code.setAttribute("id", "code_" + _title.replace(".", "-"));
		code.setAttribute("id", "code_" + "id" + domtab.tabid);
		code.setAttribute("cols", 100);
		code.setAttribute("rows", 30);
		code.value = _content;
		return content;
	},

	addEvent : function(elm, evType, fn, useCapture) {
		if (!elm)
			return;
		if (elm.addEventListener) {
			// for W3C browser
			elm.addEventListener(evType, fn, useCapture);
			return true;
		} else if (elm.attachEvent) {
			// for Internet Explorer
			var r = elm.attachEvent('on' + evType, fn);
			return r;
		} else {
			// for others
			elm['on' + evType] = fn;
		}
	},

	cssjs : function(a, o, c1) {
		if (!o)
			return;
		switch (a) {
		case 'add':
			if (!domtab.cssjs('check', o, c1)) {
				o.className += o.className ? ' ' + c1 : c1;
			}
			break;
		case 'remove':
			var rep = o.className.match(' ' + c1) ? ' ' + c1 : c1;
			o.className = o.className.replace(rep, '');
			break;
		case 'check':
			var found = false;
			var temparray = o.className;
			for ( var i = 0; i < temparray.length; i++) {
				if (temparray[i] == c1) {
					found = true;
				}
			}
			return found;
			break;
		}
	},
	changeTab : function(elm, state) {
		if (!elm)
			return;
		while (elm.nodeName.toLowerCase() != domtab.contentClass) {
			elm = elm.parentNode;
		}
		elm.style.display = state == 0 ? 'none' : 'block';
	},

	setTabWidth : function(width) {
		// must end with px
		var tabTitles = document
				.querySelectorAll('.' + domtab.tabClass + ' li');
		var tabTitles_a = document.querySelectorAll('.' + domtab.tabClass
				+ ' li a');
		for ( var i = 0; i < tabTitles.length; i++) {
			tabTitles[i].style.width = width + "px";
			tabTitles_a[i].style.width = (width - 80) + "px";
		}
	},

	getWidthInfo : function() {
		var container = document.getElementById("container");
		var container_width = window.getComputedStyle(container, null)
				.getPropertyValue("width");
		var tab_num = document.querySelectorAll('.' + domtab.tabClass + ' li').length;
		return {
			width : container_width,
			number : tab_num
		};
	},

	getTitleDOM : function(id) {
		if (!id)
			return;
		// return document.querySelector(".domtabs li#" + id.replace(".", "-"));
		return document.querySelector(".domtabs #" + id);
	},
	getContentDOM : function(id) {
		if (!id)
			return;
		// return document.querySelector(".domtab div#" + id.replace(".", "-"));
		return document.querySelector(".domtab div#" + id);
	},
	getTitle : function(id) {
		if (!id)
			return;
		// return document.querySelector(".domtabs li#" + id.replace(".", "-") +
		// " a");
		return document.querySelector(".domtabs #" + id + " a");
	},
	getContent : function(id) {
		if (!id)
			return;
		// return document.querySelector(".domtab div textarea#code_"
		// +id.replace(".", "-"));
		return document.querySelector(".domtab div #code_" + id);
	},
	getCodeMirror : function(id) {
		if (!id)
			return;
		// return document.querySelector("div#"+id.replace(".", "-") + "
		// .CodeMirror").CodeMirror;
		return document.querySelector(".domtab #" + id + " .CodeMirror").CodeMirror;
	},
	getGeneratedCodeMirror : function(id) {
		if (!id) return;
		return document.querySelector(".domtab #" + id + " .CodeMirror textarea");
	},
	getAllOpenedTabId : function() {
		var matches = document.querySelectorAll(".domtabs li");
		var ret = new Array();
		for ( var i = 0; i < matches.length; i++) {
			ret.push(matches[i].id);
		}
		return ret;
	},
};
domtab.addEvent(window, 'load', domtab.init, false);
